package cn.wit.summit.chwan.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemUpdateView;
import cn.wit.summit.chwan.widgets.ItemUpdateView.ItemDownloadInterface;
import cn.wit.summit.chwan.widgets.RecommendTopDownloadV2View;
import cn.wit.summit.chwan.widgets.RecommendTopWalletV2View;
import retrofit2.Retrofit;

/**
 * Created by pengsk on 2018/4/19.
 */

public class UpdateActivity extends MyActivity implements ItemDownloadInterface {

    Context context;
    @Bind(R.id.recvcleView)
    RecyclerView recvcleView;
    @Bind(R.id.textUpdateMessage)
    TextView textUpdateMessage;
    @Bind(R.id.rootContentNullLl)
    FrameLayout rootContentNullLl;
    @Bind(R.id.bar_title_tx)
    TextView barTitleTx;
    @Bind(R.id.retryText)
    TextView retryText;
    @Bind(R.id.recommendTopDownload)
    RecommendTopDownloadV2View topBarDownload;
    @Bind(R.id.recommendTopWallet)
    RecommendTopWalletV2View recommendTopWallet;


    List<GameListBaseBean> games = new ArrayList<>();
    LayoutInflater inflater;
    @Bind(R.id.retryImg)
    ImageView retryImg;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    @Override
    public void onAdapterItemLongChildClick(View view, DownLoadTaskTable taskTable) {

    }

    @Override
    public void dismissItem(View view, DownLoadTaskTable taskTable) {
        Iterator<GameListBaseBean> iterator = games.iterator();
        while (iterator.hasNext()) {
            GameListBaseBean bean = iterator.next();
            if (bean.getGame_id().equals(taskTable.getGameId())) {
                iterator.remove();
                break;
            }
        }
        adapter.notifyDataSetChanged();
    }

    private long tag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_layout);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        tag = System.currentTimeMillis();
        context = this;
        ButterKnife.bind(this);
        setBarTitleTx("升级");
        barTitleTx.setText("升级");
        initView();
        getUpdateInfo();
    }

    MYUpdateAdapter adapter = null;

    private void initView() {
        hideTitleBar();
        inflater = LayoutInflater.from(context);
        recvcleView.setLayoutManager(new LinearLayoutManager(context));
        adapter = new MYUpdateAdapter();
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.item_driver_h));
        recvcleView.addItemDecoration(divider);
        recvcleView.setAdapter(adapter);
        setTopBarDownload(topBarDownload, recommendTopWallet);
    }

    @OnClick({R.id.back})
    void clickView(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
        }
    }

    private void getUpdateInfo() {

        if (NetWorkUtils.isNetworkConnected(this)) {
            final List<APKUtils.APKInfo> apkInfos = APKUtils.getInstance(context).getAllInstallApkInfo(context);

            Iterator<APKUtils.APKInfo> iterator = apkInfos.iterator();
            StringBuffer buffer = new StringBuffer();
//            List<String> apkPackages = new ArrayList<>();
            while (iterator.hasNext()) {
                APKUtils.APKInfo apkInfo = iterator.next();
                buffer.append(",");
                buffer.append(apkInfo.getPackageName());
                buffer.append("|");
                buffer.append(apkInfo.getVersionName() + "_" + apkInfo.getVersionCode());
//                apkPackages.add(apkInfo.getPackageName());

            }
            String packagenames = buffer.toString();
            packagenames = packagenames.replaceFirst(",", "");
            try {

                api.getAllGameVersion(packagenames).enqueue(new MyCallback<ResponseBase<List<GameListBaseBean>>>() {
                    @Override
                    public void onSuccess(ResponseBase<List<GameListBaseBean>> model) {
                        List<GameListBaseBean> data = model.getData_info();
                        if (data != null && data.size() > 0) {
                            List<DownLoadTaskTable> taskTables = DownloadTaskManager.getInstance().findAllGame();
                            Iterator<GameListBaseBean> gaIterator = data.iterator();
                            while (gaIterator.hasNext()) {
                                GameListBaseBean gameListBaseBean = gaIterator.next();
                                Iterator<APKUtils.APKInfo> iteratorV2 = apkInfos.iterator();
                                while (iteratorV2.hasNext()) {
//                                        for (APKUtils.APKInfo apkInfo : apkInfos) {
                                    APKUtils.APKInfo apkInfo = iteratorV2.next();
                                    if (apkInfo.getPackageName().equals(gameListBaseBean.getGame_package_name()) && apkInfo.getVersionCode() < gameListBaseBean.getGame_ver()) {
                                        boolean needUpdate = true;
                                        for (DownLoadTaskTable table : taskTables) {
                                            if (table.getPackageName().equals(apkInfo.getPackageName()) && table.getNotUpdateVersion() == gameListBaseBean.getGame_ver()) {
                                                needUpdate = false;
                                                break;
                                            }
                                        }
                                        if (needUpdate) {
                                            DownLoadTaskTable table = null;
//                                                    DownLoadTaskTable table = gameListBaseBean.getDownloadTaskTableSimple();
                                            DownLoadTaskTable tableOldDb = DownloadTaskManager.getInstance().findByGameId(gameListBaseBean.getGame_id());
                                            if (tableOldDb != null) {
                                                if (tableOldDb.getDownStatus() == DownLoadStatusConfig.INSTALLED) {
                                                    table = tableOldDb.getGameListData().getDownloadTaskTableSimple();
                                                    table.setDownStatus(DownLoadStatusConfig.UPDATE);
                                                } else {
                                                    table = tableOldDb;
                                                }
                                            } else {
                                                table = gameListBaseBean.getDownloadTaskTableSimple();
                                                DownLoadTaskTable taskTableDb = gameListBaseBean.getDownloadTaskTableSimple();
                                                taskTableDb.setDownStatus(DownLoadStatusConfig.INSTALLED);
                                                DownloadTaskManager.getInstance().insertDownload(taskTableDb);

                                                table.setDownStatus(DownLoadStatusConfig.UPDATE);
                                                gameListBaseBean.setTaskTable(table);
                                            }
                                            gameListBaseBean.setTaskTable(table);
                                            games.add(gameListBaseBean);
                                        }
                                        iteratorV2.remove();
                                        break;
                                    }
                                }
                            }


                        }
                        updateUi();
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        if (code == -3) {
                            rootContentNullLl.setVisibility(View.VISIBLE);
                            recvcleView.setVisibility(View.GONE);
                            retryImg.setImageResource(R.mipmap.ic_not_net);
                            retryText.setText("网络异常，点击屏幕重新加载");
                            textUpdateMessage.setVisibility(View.GONE);
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            rootContentNullLl.setVisibility(View.VISIBLE);
            recvcleView.setVisibility(View.GONE);
            retryImg.setImageResource(R.mipmap.ic_not_net);
            retryText.setText("网络异常，点击屏幕重新加载");
            textUpdateMessage.setVisibility(View.GONE);
        }
    }

    private void updateUi() {
        try {
            if (games.size() == 0) {
                rootContentNullLl.setVisibility(View.VISIBLE);
                recvcleView.setVisibility(View.GONE);
                retryImg.setImageResource(R.mipmap.ic_not_data);
                retryText.setText("暂无游戏需要升级！");
                textUpdateMessage.setVisibility(View.GONE);
            } else {
                rootContentNullLl.setVisibility(View.GONE);
                recvcleView.setVisibility(View.VISIBLE);

            }
        } catch (Exception e) {
            recvcleView.setVisibility(View.VISIBLE);
        }
        textUpdateMessage.setText("共" + games.size() + "个游戏需要更新");
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @OnClick(R.id.rootContentNullLl)
    public void onViewClicked() {
        rootContentNullLl.setVisibility(View.GONE);
        recvcleView.setVisibility(View.VISIBLE);
        getUpdateInfo();
    }

    class MyupdateViewHolder extends RecyclerView.ViewHolder {
        ItemUpdateView updateView;

        public MyupdateViewHolder(View itemView) {
            super(itemView);
            updateView = itemView.findViewById(R.id.updateView);
        }
    }

    class MYUpdateAdapter extends RecyclerView.Adapter {

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View view = inflater.inflate(R.layout.update_item_layout, parent, false);
            MyupdateViewHolder holder = new MyupdateViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            MyupdateViewHolder h = (MyupdateViewHolder) holder;
            h.updateView.setData(UpdateActivity.this, games.get(position));
            h.updateView.setOnclickLinstener(UpdateActivity.this);
        }

        @Override
        public int getItemCount() {
            return games.size();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        for (int i = 0; i < games.size(); i++) {
            GameListBaseBean bean = games.get(i);
            if (bean.getGame_id().equals(downloadEvent.getGameId())) {
                DownLoadTaskTable table = bean.getTaskTable();
                if (table == null) {
                    table = bean.getDownloadTaskTableSimple();
                }
                table.setDownStatus(downloadEvent.status);
                if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                    table.setDownprogress(downloadEvent.getProgress());
                }
                View view = recvcleView.getLayoutManager().findViewByPosition(i);
                ItemUpdateView itemView = view.findViewById(R.id.updateView);
                DownloadViewStroke dowView = itemView.getDownView();
                dowView.updateButn(table);
            }

        }
        super.onEventMainThread(downloadEvent);
    }

}
